package com.ruoyi.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.MeetingRoomApplicationMapper;
import com.ruoyi.system.domain.MeetingRoomApplication;
import com.ruoyi.system.domain.Employee;
import com.ruoyi.system.service.IMeetingRoomApplicationService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import java.util.Date;

/**
 * 会议室申请记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-01
 */
@Service
public class MeetingRoomApplicationServiceImpl implements IMeetingRoomApplicationService 
{
    @Autowired
    private MeetingRoomApplicationMapper meetingRoomApplicationMapper;


    /**
     * 查询会议室申请记录
     * 
     * @param applicationId 会议室申请记录主键
     * @return 会议室申请记录
     */
    @Override
    public MeetingRoomApplication selectMeetingRoomApplicationByApplicationId(Long applicationId)
    {
        return meetingRoomApplicationMapper.selectMeetingRoomApplicationByApplicationId(applicationId);
    }

    /**
     * 查询会议室申请记录列表
     * 
     * @param meetingRoomApplication 会议室申请记录
     * @return 会议室申请记录
     */
    @Override
    public List<MeetingRoomApplication> selectMeetingRoomApplicationList(MeetingRoomApplication meetingRoomApplication)
    {
        //不是简单的return所有，
        //需要添加角色判断逻辑

        //1.获取当前登录用户
        SysUser currentUser = ShiroUtils.getSysUser();
        //2.设置查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("userId", currentUser.getUserId());
        params.put("ministerId", currentUser.getMinisterId());
        params.put("employeeId", currentUser.getEmployeeId());
        System.out.println(params);
        meetingRoomApplication.setParams(params);
        return meetingRoomApplicationMapper.selectMeetingRoomApplicationList(meetingRoomApplication);
    }

    /**
     * 检查会议时长是否超过24小时
     * 
     * @param startTime 会议开始时间
     * @param endTime 会议结束时间
     * @return true表示超过24小时，false表示未超过
     */
    private boolean checkMeetingDuration(Date startTime, Date endTime) 
    {
        // 计算时间差（毫秒）
        long duration = endTime.getTime() - startTime.getTime();
        // 24小时 = 24 * 60 * 60 * 1000 毫秒
        long maxDuration = 24 * 60 * 60 * 1000L;
        
        return duration > maxDuration;
    }

    /**
     * 检查会议室时间是否有冲突
     * 
     * @param meetingRoomApplication 待检查的会议室申请记录
     * @return true表示有冲突，false表示无冲突
     */
    private boolean checkTimeConflict(MeetingRoomApplication meetingRoomApplication) 
    {
        // 构建查询条件
        MeetingRoomApplication query = new MeetingRoomApplication();
        query.setRoomId(meetingRoomApplication.getRoomId());
        
        // 获取该会议室的所有申请记录
        List<MeetingRoomApplication> existingApplications = meetingRoomApplicationMapper.selectMeetingRoomApplicationList(query);
        
        Date newStart = meetingRoomApplication.getMeetingStartTime();
        Date newEnd = meetingRoomApplication.getMeetingEndTime();
        
        // 检查每个现有预订是否与新预订时间重叠
        for (MeetingRoomApplication existing : existingApplications) 
        {
            // 跳过已拒绝的申请
            if ("已拒绝".equals(existing.getStatus())) {
                continue;
            }
            
            // 跳过自己（在修改的情况下）
            if (existing.getApplicationId() != null && 
                existing.getApplicationId().equals(meetingRoomApplication.getApplicationId())) {
                continue;
            }
            
            Date existingStart = existing.getMeetingStartTime();
            Date existingEnd = existing.getMeetingEndTime();
            
            // 检查是否有重叠
            // 情况1：新会议开始时间在现有会议时间段内
            // 情况2：新会议结束时间在现有会议时间段内
            // 情况3：新会议时间段完全包含现有会议时间段
            if ((newStart.compareTo(existingStart) >= 0 && newStart.compareTo(existingEnd) < 0) ||
                (newEnd.compareTo(existingStart) > 0 && newEnd.compareTo(existingEnd) <= 0) ||
                (newStart.compareTo(existingStart) <= 0 && newEnd.compareTo(existingEnd) >= 0)) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * 新增会议室申请记录
     * 
     * @param meetingRoomApplication 会议室申请记录
     * @return 结果
     */
    @Override
    public int insertMeetingRoomApplication(MeetingRoomApplication meetingRoomApplication)
    {
        // 检查开始时间是否晚于结束时间
        if (meetingRoomApplication.getMeetingStartTime().after(meetingRoomApplication.getMeetingEndTime())) {
            throw new ServiceException("会议开始时间不能晚于结束时间");
        }
        
        // 检查会议时长是否超过24小时
        if (checkMeetingDuration(meetingRoomApplication.getMeetingStartTime(), meetingRoomApplication.getMeetingEndTime())) {
            throw new ServiceException("会议时间过长哦~牛马也不是这样压榨的！");
        }

        // 设置初始状态为待审批
        meetingRoomApplication.setStatus("待审批");
        
        // 检查时间冲突
        if (checkTimeConflict(meetingRoomApplication)) {
            throw new ServiceException("所选时间段与已有会议时间冲突，请重新选择时间");
        }
        
        return meetingRoomApplicationMapper.insertMeetingRoomApplication(meetingRoomApplication);
    }

    /**
     * 修改会议室申请记录
     * 
     * @param meetingRoomApplication 会议室申请记录
     * @return 结果
     */
    @Override
    public int updateMeetingRoomApplication(MeetingRoomApplication meetingRoomApplication)
    {
        // 检查开始时间是否晚于结束时间
        if (meetingRoomApplication.getMeetingStartTime().after(meetingRoomApplication.getMeetingEndTime())) {
            throw new ServiceException("会议开始时间不能晚于结束时间");
        }
        
        // 检查会议时长是否超过24小时
        if (checkMeetingDuration(meetingRoomApplication.getMeetingStartTime(), meetingRoomApplication.getMeetingEndTime())) {
            throw new ServiceException("会议时间过长哦~牛马也不是这样压榨的！");
        }
        
        // 检查时间冲突（如果不是已拒绝状态才检查）
        if (!"已拒绝".equals(meetingRoomApplication.getStatus()) && checkTimeConflict(meetingRoomApplication)) {
            throw new ServiceException("所选时间段与已有会议时间冲突，请重新选择时间");
        }
        
        return meetingRoomApplicationMapper.updateMeetingRoomApplication(meetingRoomApplication);
    }

    /**
     * 批量删除会议室申请记录
     * 
     * @param applicationIds 需要删除的会议室申请记录主键
     * @return 结果
     */
    @Override
    public int deleteMeetingRoomApplicationByApplicationIds(String applicationIds)
    {
        return meetingRoomApplicationMapper.deleteMeetingRoomApplicationByApplicationIds(Convert.toStrArray(applicationIds));
    }

    /**
     * 删除会议室申请记录信息
     * 
     * @param applicationId 会议室申请记录主键
     * @return 结果
     */
    @Override
    public int deleteMeetingRoomApplicationByApplicationId(Long applicationId)
    {
        return meetingRoomApplicationMapper.deleteMeetingRoomApplicationByApplicationId(applicationId);
    }



    @Override
    public List<Employee> selectEmployeesByMinisterId(Long ministerId)
    {
        return meetingRoomApplicationMapper.selectEmployeesByMinisterId(ministerId);
    }
}
